//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package cn.ekuma.epos.datalogic.define;

import e.odbo.data.dao.DataLogic;
import e.odbo.data.dao.EntityManager;
import e.odbo.data.dao.I_ParentNode;
import e.odbo.data.bean.IKeyed;
import cn.ekuma.epos.bean.util.sale.KitchenLineHelper;
import cn.ekuma.epos.bean.util.sale.TicketHelper;

import com.openbravo.bean.PlaceState;
import com.openbravo.bean.erp.Order;
import com.openbravo.bean.erp.SharedLinkOrder;
import com.openbravo.bean.erp.SharedOrder;
import com.openbravo.bean.sales.KitchenLine;
import com.openbravo.bean.sales.KitchenWorkLine;
import com.openbravo.bean.sales.SharedTicket;
import com.openbravo.bean.sales.SharedTicketInfo;
import com.openbravo.bean.sales.TicketLine;
import cn.ekuma.epos.datalogic.I_DataLogicReceipts;
import cn.ekuma.epos.datalogic.define.dao.PlaceStateDAO;
import cn.ekuma.epos.datalogic.define.dao.erp.FindOrdersInfoDAO;
import cn.ekuma.epos.datalogic.define.dao.erp.SharedLinkOrderDAO;
import cn.ekuma.epos.datalogic.define.dao.erp.SharedOrderDAO;
import cn.ekuma.epos.datalogic.define.dao.sale.ShardTicketDAO;
import cn.ekuma.epos.datalogic.define.dao.sale.ShardTicketInfoDAO;
import cn.ekuma.epos.datalogic.define.dao.sale.kitchen.KitchenWorkLineDAO;
import java.util.Date;
import java.util.List;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.serialize.Datas;
import com.openbravo.data.loader.key.KeyBuilder;
import com.openbravo.data.loader.sentence.SentenceList;
import com.openbravo.data.loader.serialize.serializer.read.SerializerReadBasic;
import com.openbravo.data.loader.serialize.serializer.write.SerializerWriteString;
import com.openbravo.data.loader.sentence.StaticSentence;
import com.openbravo.bean.sales.Ticket;

/**
 *
 * @author adrianromero
 */
public class DataLogicReceipts extends DataLogic implements I_DataLogicReceipts  {
    
    private ShardTicketInfoDAO shardTicketInfoDAO;
    private ShardTicketDAO shardTicketDAO;
    private FindOrdersInfoDAO findOrdersInfoDAO;
    private SharedOrderDAO shardOrderDAO;
    private KitchenWorkLineDAO kitchenWorkLineDAO;
	private SharedLinkOrderDAO shardLinkOrderDAO;
	private PlaceStateDAO placeStateDAO;
    
    
    public DataLogicReceipts(EntityManager entityManager){
    	super(entityManager);
        shardTicketDAO=new ShardTicketDAO (s);
        addDaoToMap(shardTicketDAO);
        shardTicketInfoDAO=new ShardTicketInfoDAO(shardTicketDAO);
		addDaoToMap(shardTicketInfoDAO);
        findOrdersInfoDAO=new FindOrdersInfoDAO(s);
		addDaoToMap(findOrdersInfoDAO);
        shardOrderDAO=new SharedOrderDAO(s);
		addDaoToMap(shardOrderDAO);
        kitchenWorkLineDAO=new KitchenWorkLineDAO(s);
		addDaoToMap(kitchenWorkLineDAO);
        shardLinkOrderDAO=new SharedLinkOrderDAO(s);
		addDaoToMap(shardLinkOrderDAO);
        placeStateDAO=new PlaceStateDAO(s);
		addDaoToMap(placeStateDAO);
    }
     
    public final Ticket getSharedTicket(String Id) throws BasicException {
        if (Id == null) {
            return null; 
        } else {
            Object[]record = (Object[]) new StaticSentence(s
                    , "SELECT CONTENT FROM SHAREDTICKETS WHERE ID = ?"
                    , SerializerWriteString.INSTANCE
                    , new SerializerReadBasic(new Datas[] {Datas.SERIALIZABLE})).find(Id);
            return record == null ? null : (Ticket) record[0];
        }
    } 
    
    public final List<SharedTicketInfo> getSharedTicketList(String locationId) throws BasicException {
        return shardTicketInfoDAO.getSharedTicketList(locationId);
    }
    
    public final void updateSharedTicket(final String id, final Ticket ticket, String userId) throws BasicException {
    	updateSharedTicket(id,ticket,true,userId);
    }
    
    @Override
	public void updateSharedTicketAndUnLocked(String id,
			Ticket ticket) throws BasicException {
    	updateSharedTicket(id,ticket,false,ticket.getM_User().getId());
	}

	private void updateSharedTicket(final String id, final Ticket ticket,final boolean locked,String userId) throws BasicException{ 
        SharedTicket sharedTicket=new SharedTicket();
     	sharedTicket.setId(id);
     	sharedTicket.setLocationId(ticket.getLocation());
     	sharedTicket.setContent(ticket);
     	sharedTicket.setLocked(locked);
     	sharedTicket.setLockUserId(locked==true?userId:null);
     	sharedTicket.setName(TicketHelper.getName(ticket));
     	sharedTicket.setM_sGroupName(ticket.getM_sGroupName());
     	shardTicketDAO.update(sharedTicket);
    }
    
    public final void insertSharedTicket(final String id, final Ticket ticket) throws BasicException {
        SharedTicket sharedTicket=new SharedTicket();
     	sharedTicket.setId(id);
     	sharedTicket.setLocationId(ticket.getLocation());
     	sharedTicket.setContent(ticket);
     	sharedTicket.setLocked(true);
     	sharedTicket.setLockUserId(ticket.getM_User().getId());
     	sharedTicket.setName(TicketHelper.getName(ticket));
     	sharedTicket.setM_sGroupName(ticket.getM_sGroupName());
     	shardTicketDAO.insert(sharedTicket);
    }  
    
    
    @Override
	public void insertSharedTicketNoLock(String id, Ticket ticket)
			throws BasicException {
    	SharedTicket sharedTicket=new SharedTicket();
     	sharedTicket.setId(id);
     	sharedTicket.setLocationId(ticket.getLocation());
     	sharedTicket.setContent(ticket);
     	sharedTicket.setLocked(false);
     	sharedTicket.setName(TicketHelper.getName(ticket));
     	sharedTicket.setM_sGroupName(ticket.getM_sGroupName());
     	shardTicketDAO.insert(sharedTicket);
	}

	public final void deleteSharedTicket(final String id) throws BasicException {
        new StaticSentence(s
            , "DELETE FROM SHAREDTICKETS WHERE ID = ?"
            , SerializerWriteString.INSTANCE).exec(id);      
    }
    
    @Override
	public void setSharedTicketLocked(String id, boolean locked, String userId)
			throws BasicException {
    	shardTicketDAO.setSharedOrderLocked(id, locked,userId);
	}

    
    public  boolean isSharedTicketLocked(String id) throws BasicException {
    	return shardTicketDAO.isSharedTicketLocked(id);
    }
    
    
    
    /**
     * 开始单据相关
     */
    
    
	@Override
    public void insertSharedOrder(final String id,final Order order) throws BasicException {
    	SharedOrder sharedOrder=new SharedOrder();
    	sharedOrder.setId(id);
    	sharedOrder.setOrder(order);
    	sharedOrder.setLocked(true);
    	sharedOrder.setLockUserId(order.getUser().getId());
    	shardOrderDAO.insert(sharedOrder);
    }

    @Override
    public Order getSharedOrder(String Id) throws BasicException {
    	return shardOrderDAO.getSharedOrder(Id);
    }

    @Override
    public void deleteSharedOrder(String id) throws BasicException {
         new StaticSentence(s
            , "DELETE FROM SHAREDORDERS WHERE ID = ?"
            , SerializerWriteString.INSTANCE).exec(id);
    }

    @Override
    public List<String> getSharedOrderList() throws BasicException {
    	return shardOrderDAO.getSharedOrderList();
    }

    public SentenceList getSharedOrderListQBF() {
        return findOrdersInfoDAO.getSharedOrderListQBF();
    }

    public SentenceList getSharedLinkOrderListQBF() {
        return findOrdersInfoDAO.getSharedLinkOrderListQBF();
    }

    
    @Override
    public void setSharedOrderLocked(String id, boolean locked,String userId) throws BasicException {
    	shardOrderDAO.setSharedOrderLocked(id, locked,userId);
    }

    @Override
    public void updateSharedOrder(final String id, final Order order,String userId) throws BasicException {
         updateSharedOrder(id,order,true,userId);
    }

    @Override
    public void updateSharedOrderAndUnLocked(String id, Order order) throws BasicException {
        updateSharedOrder(id,order,false,null);
    }

    private void updateSharedOrder(final String id, final Order order,final boolean locked,String userId) throws BasicException{
    	SharedOrder sharedOrder=new SharedOrder();
    	sharedOrder.setId(id);
    	sharedOrder.setOrder(order);
    	sharedOrder.setLocked(locked);
    	sharedOrder.setLockUserId(locked==true?userId:null);
    	shardOrderDAO.update(sharedOrder);
    }

	@Override
	public void insertLinkSharedOrder(String id, Order order)throws BasicException {
		SharedLinkOrder sharedOrder=new SharedLinkOrder();
    	sharedOrder.setId(id);
    	sharedOrder.setOrder(order);
    	sharedOrder.setLocked(true);
    	sharedOrder.setLockUserId(order.getUser().getId());
    	shardLinkOrderDAO.insert(sharedOrder);
	}

	@Override
	public void insertSharedOrderNoLock(String id, Order order)
			throws BasicException {
	    	SharedOrder sharedOrder=new SharedOrder();
	    	sharedOrder.setId(id);
	    	sharedOrder.setOrder(order);
	    	sharedOrder.setLocked(false);
	    	shardOrderDAO.insert(sharedOrder);
	}
	
	@Override
	public Class transParentClass(Class in) {
		return DateLogicUtils.transParentClass(in);
	}

	@Override
	public List<PlaceState> loadPlacesStateBetween(Date begin,Date after)throws BasicException {
		return placeStateDAO.loadPlacesStateBetween(begin,after);
	}

	@Override
	public void joinGroup(String id, String group) throws BasicException {
		placeStateDAO.joinGroup(id, group);
		
	}

	@Override
	public void updatePlaceState(String id, String newState)
			throws BasicException {
		placeStateDAO.updatePlaceState(id, newState);
		
	}

	@Override
	public void setPlaceManager(String id, String manager)
			throws BasicException {
		placeStateDAO.setPlaceManager(id, manager);	
	}
	
	public void sendToKitchen(String id,Ticket t)throws BasicException {
    	for(TicketLine l:t.getLines()){
    		if(l.getProductID()!=null&&(l.getProperty(KitchenLine.KITCHEN_PROPERTY)==null&&l.isManufacturing())){
    			kitchenWorkLineDAO.insert(KitchenLineHelper.getKitchenWorkLineForTicketLine(id, l));
    		}
    	}
    }
    
    public List<KitchenWorkLine> listByTicket(final String ticketId)throws BasicException {
    	return kitchenWorkLineDAO.list(new I_ParentNode(){
			@Override
			public IKeyed getParentKey() {
				return KeyBuilder.getKey(ticketId);
			}
			@Override
			public Class getParentClass() {
				return Ticket.class;
			}
    	});
    }
    
    public void urgentToKitch(String ticketId)throws BasicException {
    	kitchenWorkLineDAO.urgentToKitch(ticketId);
    }

	@Override
	public void updateLineState(String id, String host, int order, int state)
			throws BasicException {
		kitchenWorkLineDAO.updateLineState(id, host, order, state);
	}

	@Override
	public void cooking(String id, String host, int order)
			throws BasicException {
		kitchenWorkLineDAO.cooking(id, host, order);
	}

	@Override
	public void backForWait(String id) throws BasicException {
		kitchenWorkLineDAO.backForWait(id);
	}

	@Override
	public void updateTicketState(String ticketId, int state)
			throws BasicException {
		kitchenWorkLineDAO.updateTicketState(ticketId, state);
	}

	@Override
	public void ticketDelete(String ticketId) throws BasicException {
		kitchenWorkLineDAO.ticketDelete(ticketId);
	}

	@Override
	public List<KitchenWorkLine> listKitchenWorkLineByLineState(int lineState)
			throws BasicException {
		return kitchenWorkLineDAO.listKitchenWorkLineByLineState(lineState);
	}

	@Override
	public List<KitchenWorkLine> listKitchenWorkLineByHostCooking(String host)
			throws BasicException {
		return kitchenWorkLineDAO.listKitchenWorkLineByHostCooking(host);
	}
	
	public List<KitchenWorkLine> listKitchenWorkLineByTicketID(String ticketId)
			throws BasicException {
		return kitchenWorkLineDAO.listKitchenWorkLineByTicketID(ticketId);
	}

	@Override
	public void lockSharedTicket(String id,String userId) throws BasicException {
		shardTicketDAO.lockSharedTicket(id,userId);
		
	}
}
